package com.nali.dal.statement.function.formatter.date;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Component;

import com.nali.dal.statement.function.AbstractDataHandler;
import com.nali.dal.statement.function.FunctionArgument;
import com.nali.dal.statement.function.FunctionException;
import com.nali.dal.statement.util.DalDateUtils;

/**
 * ToDate<br>&nbsp;
 * 支持1-2个参数<br>&nbsp;
 * 支持数字和字符串作为入参<br>&nbsp;
 * 支持对数字使用pattern和timeUnit形式格式化<br>&nbsp;
 * 支持对字符串使用pattern<br>&nbsp;
 * 支持对字符串使用pattern<br>&nbsp;
 * 如果第一个参数是date类型，直接返回第一个参数<br>&nbsp;
 * @author sam Created on 2011-4-15
 */
@Component
public class ToDate extends AbstractDataHandler<Date> {

	public Date handle(Object arg1) throws FunctionException {
		if (arg1 instanceof Date) {
			return (Date) arg1;
		} else {
			if (arg1 instanceof Number) {
				Number num = (Number) arg1;
				if(num.intValue()==0) {
					return null;//TODO 1970 or null
				}
			}
			return DalDateUtils.parseAuto(arg1.toString());
		}
	}

	public Date handle(Object arg1, Object arg2) throws FunctionException, ParseException {
		String pattern=(String) arg2;
		String dateString;
		if (arg1 instanceof Number) {
			Number number = (Number) arg1;
			TimeUnit timeUnit = TimeUnit.findTimeUnit(pattern);
			if(timeUnit!=null) {
				return timeUnit.getDate(number.longValue());
			}
			if(number.intValue()==0) {
				return null;//TODO 1970 or null
			}
			dateString=number.toString();
		} else if (arg1 instanceof String) {
			dateString = (String) arg1;
		} else if (arg1 instanceof Date) {
			return (Date) arg1;
		} else {
			throw new FunctionException("unsupported type:"+arg1);
		}
		return DalDateUtils.parse(dateString, pattern);
	}

	@Override
	public Date handle(List<Object> argList) throws FunctionException {
		try {
			Object arg1 = argList.get(0);
			if(argList.size()==1) {
				return handle(arg1);
			} else {
				return handle(arg1, argList.get(1));
			}
		} catch (ParseException e) {
			throw new FunctionException(e.getMessage(), e);
		}
	}

	@Override
	public void validate(List<FunctionArgument> arguments) throws FunctionException {
		checkSize(arguments, 1, 2);
	}
}
